var checkLength=/([\u4E00-\u9FA5\uf900-\ufa2d])/g;
var checkPhone=/^((\(\d{2,3}\))|(\d{3}\-))?(13\d{9}|15\d{9}|17\d{9}|18\d{9})$/;
var editAdminInfo,roleGrid;
var pageObj1={type:"1100",width:[180],height:[0,0,0],htmlObj:["detail_div"]};
var layoutContainer1 = create_layout(pageObj1);
var roleToolbar;
var randomNum = getRandomNum();
var oldUserType;


$(function(){
    roleToolbar = layoutContainer1.layout.items[0].attachToolbar({});
    roleToolbar.setIconsPath(basePP + "images/main/button/toolbar/");
    roleToolbar.addInput("searchKey",3,"输入角色名",100);
    roleToolbar.addButton("search", 4, "查询", "viewStock.png", "");
    roleToolbar.setAlign("right");
    roleToolbar.attachEvent("onClick", doOnClickRoleTool);
    //增加搜索键盘事件
    initRoleGrid();
    searchRole();
    roleToolbar.attachEvent("onEnter", function(id, value){
        searchRole();
    });
    //----------------------------------------------------------------!!!样式!!!
    $('.inp').focus(function(){	this.value='';}); //获取焦点后置空输入框
    layoutContainer1.layout.items[0].fixSize(true, false);//固定布局尺寸
    $('.dhtmlxLayoutPolySplitterVerInactive div').css("width","3px");//分割线
});
function initRoleGrid() {
    roleGrid = layoutContainer1.grid[0];
    dmjplugs.grid.createGrid({
        sm:'ch',
        skin:'dhx_skyblue',
        srcc:true,
        validate : true,
        columns:[ {header:'id',id:'roleId',width:10,hidden:true},
            {header:'角色名',id:'name',width:'*'}
        ]
    },roleGrid);
    roleGrid.setTotal(0);
    roleGrid.enableEditEvents(false,false,false);
    roleGrid.attachEvent("onRowSelect",onSelectRoleRow);
    roleGrid.setColumnHidden(0,true);
}
//初始化Form1
function doOnFormInit1(){

    $(editForm1.getInput("alipayId")).attr("maxlength",19);

    //按钮事件
    if (typeof(editForm1) == "object"){
        editForm1.attachEvent("onButtonClick", function(name, command) {
            switch(command) {
                case 'save':doSave();break;
                case 'cancle':doCancle();break;
            }
        });
    }
    if (type == 'edit') {
        editForm1.disableItem("alipayId");
    }
    editForm1.setItemValue("alipayIdtag","USERID为32位之内的数字组合");

    //校验事件
    $("input[name='realName']").focus(function () {
        $("input[name='realNametag']").css({color:"#666666"});
        editForm1.setItemValue("realNametag","2~20位纯字母、数字、汉字或组合");
    });
    $("input[name='realName']").blur(function () {
        var realName=$.trim($(this).val());
        var realName_lng=realName.replace(checkLength,'**').length;
        editForm1.setItemValue("realNametag","");
        $("input[name='realNametag']").css({color:"red"});
        if(realName.length==0){
            editForm1.setItemValue("realNametag","请填写用户名");
        }else if(realName_lng>20 || realName_lng < 2){
            editForm1.setItemValue("realNametag","2~20位纯字母、数字、汉字或组合");
        }
    });

    if (type == 'add') {
        $("input[name='alipayId']").focus(function () {
            $("input[name='alipaytag']").css({color:"#666666"});
            editForm1.setItemValue("alipaytag","请输入支付宝USERID");
        });
        $("input[name='alipayId']").blur(function () {
            var realName=$.trim($(this).val());
            var realName_lng=realName.replace(checkLength,'**').length;
            editForm1.setItemValue("alipaytag","");
            $("input[name='alipaytag']").css({color:"red"});
            if(realName.length==0){
                editForm1.setItemValue("alipaytag","请输入支付宝USERID");
            }else if(!isDigit(realName)){
                editForm1.setItemValue("alipaytag","支付宝USERID必须为全数字 ");
            }
        });
    }

    $("input[name='phone']").blur(function () {
        var telephone=$.trim($(this).val());
        editForm1.setItemValue("phonetag","");
        $("input[name='phonetag']").css({color:"red"});
        if(telephone.length>0&&(telephone.length!=11||!checkPhone.exec(telephone))){
            editForm1.setItemValue("phonetag","11位有效的手机号码");
        }
    });
    editForm1.disableItem("alipayAccounttag");
    editForm1.disableItem("realNametag");
    editForm1.disableItem("phonetag");
    editForm1.disableItem("alipaytag");
    editForm1.disableItem("userTypetag");

    var userType=editForm1.getCombo('userType');
    userType.addOption(parent.roleTypeComboData);
    userType.setComboValue('');
    userType.readonly(true);
    userType.attachEvent("onChange",setRoleType);

    if (type=='edit') doOnForm1EditInit();
    if (type=='add') doOnForm1AddInit();
}

function setRoleType() {
    var userType_combo=editForm1.getCombo('userType');
    var userType = userType_combo.getSelectedValue();
    // if (oldUserType == 'sysadmin') {
        var roles =  getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
        if (roles != null && roles.length > 0) {
            editForm1.setItemValue("roleId",roles[0].roleId);
            editForm1.setItemValue("roleName",roles[0].name);
        } else {
            editForm1.setItemValue("roleId",null);
            editForm1.setItemValue("roleName","");
        }
    // }
    // if (userType == 'sysadmin') {
    //     editForm1.setItemValue("roleName","系统管理员");
    //     editForm1._disableItem("roleName");
    // }
    oldUserType = userType;
}

function doOnForm1AddInit() {
    if(type=='add'){
        checkParam(randomNum);
    }
}
//完善编辑用户详情
function doOnForm1EditInit(){
    var userType = editForm1.getCombo('userType');
    userType.setComboValue(parent.oneAdminInfo.user_type);

    editForm1.setReadonly("alipayId",true);
    if (!id||id<=0)	return;

    editForm1.setItemValue("id",parent.oneAdminInfo.id);
    editForm1.setItemValue("alipayId",escape2Html(parent.oneAdminInfo.alipay_id));
    editForm1.setItemValue("alipayAccount",escape2Html(parent.oneAdminInfo.alipay_account));
    editForm1.setItemValue("phone",escape2Html(parent.oneAdminInfo.phone));
    editForm1.setItemValue("realName",escape2Html(parent.oneAdminInfo.real_name));

    $.ajax({
        url: basePath+'managerAlipayUser/oneAlipayUserInfo/'+id,
        type: 'get',
        dataType: 'json',
        // data:postData,
        success: function (back, textStatus, xhr) {
            if(!back){
                $func.alert("请求失败,状态:"+textStatus);
                return;
            }
            if(!back.result){
                $func.alert(back.message?back.message:"请求失败", "red");

                return;
            }
            if(!back.content) return;
            editAdminInfo=back.content;
            editForm1.setItemValue("roleId",editAdminInfo.roleId);
            editForm1.setItemValue("roleName",escape2Html(editAdminInfo.roleName));
            //左侧角色与右侧管理员管理角色关联起来，标记为选中状态
            roleGrid.forEachRow(function (id) {
                var leftRowRoleName = $.trim(roleGrid.cells(id,roleGrid.getColIndexById('name')).getValue());
                var rightRoleName = editForm1.getInput("roleName").value;
                if (leftRowRoleName && leftRowRoleName.length>0 && leftRowRoleName == rightRoleName) {
                    var rowIndex=roleGrid.getRowIndex(id);
                    roleGrid.selectRow(rowIndex,true);
                    return;
                }
            });
        },
        error:function (xhr, textStatus, errorThrown) {
            $func.alert("请求失败！", "red");
        }
    });
}
//初始化按钮form
function doOnButtonForm(){
    if (typeof(buttonForm) == "object"){
        buttonForm.attachEvent("onButtonClick", function(name, command) {
            switch(command) {
                case 'save':doSave();break;
                case 'cancle':doCancle();break;
            }
        });
    }
}
//校验新增/编辑form表单
function checkForm(){
    $("input[name$='tag']").val("");
    var alipayId=$.trim(editForm1.getItemValue("alipayId"));
    var alipayAccount=$.trim(editForm1.getItemValue("alipayAccount"));
    var realName=$.trim(editForm1.getItemValue("realName"));
    var phone=$.trim(editForm1.getItemValue("phone"));
    var roleId=$("input[name='roleId']:checked").val();

    var userType_combo=editForm1.getCombo('userType');
    var userType = userType_combo.getSelectedValue();

    if (alipayId == null || alipayId == '') {
        $func.alert("请先填写支付宝USERID", "red");
        return;
    }

    if (!isDigit(alipayId)) {
        $func.alert("支付宝USERID必须为全数字", "red");
        return;
    }

    if (userType == null || userType == '') {
        $func.alert("请先选择管理员类型", "red");
        return;
    }

    if(realName.length==0){
        $func.alert('请填写用户名', 'red');
        return false;
    }

    if (checkInput(realName)) {
        $func.alert('用户名必须为2~20位纯字母、数字、汉字或组合', 'red');
        return false;
    }
    var branchHoss = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
    // if (userType != 'sysadmin') {
        var roleNameCheck = editForm1.getInput('roleName').value;
        if(!roleNameCheck){
            $func.alert("请点击左边栏选择角色值", "red");
            return;
        }
        if(!branchHoss){
            $func.alert("请选择一个角色", "red");
            return;
        }
        if(branchHoss.length !=1){
            $func.alert("只能勾选一个角色", "red");
            return;
        }
    // }

    var realName_lng = realName.length;
    if(realName_lng>20 || realName_lng < 2){
        $func.alert('用户名必须为2~20位纯字母、数字、汉字或组合', 'red');
        return false;
    }
    if(phone.length>0&&(phone.length!=11||!checkPhone.exec(phone))){
        $func.alert('联系手机格式不正确，请重填！', 'red');
        return false;
    }
    return true;
}

function isDigit(str) {
    var patrn=/^([+-]?)(\d+)$/;
    return patrn.test(str);
}

//保存动作
function doSave(){
    if(!checkForm())return;
    var formData = editForm1.getFormData();
    var postData="alipayId="+(formData.alipayId&&formData.alipayId.length>0?formData.alipayId:"");
    postData += "&alipayAccount="+(formData.alipayAccount&&formData.alipayAccount.length>0?formData.alipayAccount:"");
    postData += "&realName="+(formData.realName&&formData.realName.length>0?formData.realName:"");
    postData+="&phone="+(formData.phone&&formData.phone.length>0?formData.phone:"");
    postData+="&roleId="+formData.roleId;
    postData += "&status=enabled";
    postData += "&userType="+formData.userType;

    if(type=='add' ){
        postData+="&randomNum="+randomNum;
    }
    if(type=='edit') postData+="&id="+formData.id;

    postData=encodeURI(postData);
    $.ajax({
        url: basePath+'managerAlipayUser/saveAlipayUser',
        type: 'post',
        dataType: 'json',
        data:postData,
        success: function (back) {
            if(!back||!back.result){
                $func.alert(back.message?back.message:"保存失败", "red");
                return;
            }
            $func.alert("保存成功！", "green");
            parent.findPageGrid();
            doCancle();
        }
    });
}
//取消动作
function doCancle(){
    parent.addAdminWin.close();
}

function doOnClickRoleTool(id){
    switch (id) {
        case 'search':searchRole();break;
    }
}
function searchRole(vContent){//加载疾病知识信息数据 ,先索引后数据库

    var searchType=1; //search_Form.getItemValue("docSearchType") ;
    var searchKey=roleToolbar.getValue("searchKey"); //search_Form.getItemValue("docSearchKey") ;
    if(vContent) searchKey=vContent;
    if(searchKey=='输入角色名') searchKey='';
    if(!searchKey||searchKey.length==0){
        /*	$func.alert("请填写“角色名”进行查询", "red");
         return;*/
    }
    roleGrid.setTotal(0);
    roleGrid.clearAll();
    var postData="pageNo=1&pageSize=200&pageCount=0";
    if(searchKey&&searchKey.length>0){
        postData+="&roleName="+searchKey;
    }
    postData+="&status=enabled";
    $.ajax({
        url: basePath+'manageRole/findPageData',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
        success: function(back, textStatus, jqXHR) {
            if(!back){
                $func.alert("请求失败,状态:"+textStatus);
                return;
            }
            if(back.rowCount>0){
                roleGrid.parse(back.gridr, "json");
                roleGrid.setTotal(back.rowCount);
                roleGrid.uncheckAll();
                $("input[type='checkbox']").removeAttr('checked');
            }
        },
        error:function (xhr, textStatus, statustText) {
            $func.alert("请求失败,状态:"+textStatus , "red");
        }
    });
}
function onSelectRoleRow(rowID, celInd) {
    var  roleId=roleGrid.cells(rowID, roleGrid.getColIndexById('roleId')).getValue();
    var  name=roleGrid.cells(rowID, roleGrid.getColIndexById('name')).getValue();

    var userType_combo=editForm1.getCombo('userType');
    var userType = userType_combo.getSelectedValue();
    // if (userType != 'sysadmin') {
        editForm1.setItemValue("roleId",roleId);
        editForm1.setItemValue("roleName",name);
    // }
}

var checkInput = function (str) {
    var pattern = /^[\w\u4e00-\u9fa5]+$/gi;
    if(pattern.test(str))
    {
        return false;
    }
    return true;
}